package com.demo.controller;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Sorts;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Init;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;

import java.util.ArrayList;
import java.util.List;

import static com.mongodb.client.model.Projections.fields;
import static com.mongodb.client.model.Projections.include;


@Controller
public class TestController2 {
    @Inject("${mongodb.uri}")
    private String mongoUrl;

    MongoClient mongoClient;
    MongoDatabase database;

    MongoCollection<Document> simpleDataCollection;

    @Init
    public void init() {
        mongoClient = new MongoClient(new MongoClientURI(mongoUrl));
        database = mongoClient.getDatabase("tasks");
        simpleDataCollection = database.getCollection("col_Vietnamese_20210425_1-mark-20210605");
    }


    @Mapping("/1")
    public Object test2() {
        BasicDBObject query = new BasicDBObject();
        Bson sort = new Document("_id", -1);
        Bson resultFields = fields(include("url"));
//        Bson idParam = new Document("$gte",randomId);
        query.put("markerId", 6194);
        List result = new ArrayList<>();
        MongoCursor<Document> documents = simpleDataCollection.find(query)
                .projection(resultFields).limit(1000)
                .sort(Sorts.orderBy(sort))
                .iterator();
        documents.forEachRemaining(document -> {
            LabelData data = new LabelData();
            data.setUrl(document.getString("url"));
            result.add(data);
        });
        return result;
    }

}
